const app = getApp();
const WxNotificationCenter = require('../../../../common/utils/WxNotificationCenter/WxNotificationCenter');
WxNotificationCenter.postNotificationName(app.INJECT_BLOBAL_EVENT, {
  global: require('../../../global'),
});
let liveroom = require('../../../utils/liveroom.js');
const getlogininfo = require('../../../getlogininfo');

Page({
  component: null,
  data: {
    userName: '',
    roomID: '',
    roomName: '',
    pureAudio: false,
    role: 'audience',
    showLiveRoom: false,
    rooms: [],
    linked: false,
    debug: false,
    muted: false,
    beauty: 5,
    createType:'',
    isShowVoice: false,
    isGetLoginInfo: false,
  },
  onLoad: function (options) {
    let self = this;
    console.log('--> onLoad: ', options);
    let role = options.type == 'create' ? 'presenter' : 'audience';
    if (role == 'audience') {  //非创建者
      let pages = getCurrentPages();
      let route = pages[pages.length - 1].route;
      app.videoVisiterRecord(options.roomID, route.split('/')[0]);// 音视频参与人员记录接口,参数是roomId
      self.setData({
        roomID: options.roomID,
        roomName: options.roomName,
        // userName: options.userName,
        pureAudio: JSON.parse(options.pureAudio),
        role: role,
        showLiveRoom: true,
        createType: options.type||'',
      }, function () {
        self.getLoginInfo().then(() => {
        self.start();
      });
      });
    } else {
      self.setData({
        roomName: options.roomName,
        userName: options.userName,
        pureAudio: JSON.parse(options.pureAudio),
        role: role,
        showLiveRoom: true,
        createType: options.type||'',
        isGetLoginInfo: true,
      }, function () {
        console.log('======> page data: ', self.data);
        self.start();
        self.changeMute();
        wx.showToast({
          title: '当前为静音状态，如需发言请打开声音',
          icon: 'none',
          duration: 3000,
        });
      });
    }
  },

  onReady: function () {
    let self = this;
    wx.setNavigationBarTitle({
      title: self.data.roomName,
    });
  },

  onRoomEvent: function (e) {
    let self = this;
    let args = e.detail;
    console.log('onRoomEvent', args);
    switch (args.tag) {
      case 'roomClosed': {
        wx.showModal({
          content: `房间已解散`,
          showCancel: false,
          complete: () => {
            wx.navigateBack({ delta: 1 });
          },
        });
        break;
      }
      case 'error': {
        if (args.code === 5000) {
        wx.showModal({
          content: '直播已断开',
          showCancel: false,
          complete: () => {
            wx.navigateBack({ delta: 1 });
          },
        });
        } else {
          wx.showToast({
            title: `${args.detail}[${args.code}]`,
            icon: 'none',
            duration: 1500,
          });
        }
        break;
      }
      case 'LinkOn': { // 连麦连上
        self.setData({
          linked: true,
        });
        self.changeMute();
        self.component && self.component.changeVoice();
        wx.showToast({
          title: '当前为静音状态，如需发言请打开声音',
          icon: 'none',
          duration: 3000,
        });
        break;
      }
      case 'LinkOut': { // 连麦断开
        self.setData({
          linked: false,
        });
        self.component && self.component.changeVoice();
        break;
      }
      case 'joinPusher': {
        let joiner = args.detail;
        wx.showModal({
          content: `${joiner.userName} 请求连麦`,
          success: function (sm) {
            if (sm.confirm) {
              console.log('用户点击同意');
              self.component && self.component.respondJoinReq(true, joiner);
            } else if (sm.cancel) {
              console.log('用户点击取消');
            }
          },
        });
        break;
      }
      default: {
        console.log('onRoomEvent default: ', e);
        break;
      }
    }
  },
  start: function () {
    let self = this;
    self.component = self.selectComponent('#id_liveroom');
    console.log('self.component: ', self.component);
    console.log('self:', self);
    self.component.start();
  },
  onShow: function () {
    let self = this;
    self.component && self.component.resume();
  },
  onHide: function () {
    let self = this;
    self.component && self.component.pause();
  },
  onUnload: function () {
    let self = this;
    // self.component && self.component.stop();
  },
  changeMute () {
    this.setData({
      muted: !this.data.muted,
    });
  },
  onShareAppMessage() {
    const roomInfo = liveroom.getRoomInfo();
    return {
      title: this.data.roomName,
      path: `/cm_trtc_1/pages/live-phone/room/room?roomID=${roomInfo.roomID}&roomName=${this.data.roomName}&pureAudio=${this.data.pureAudio}`,
      success: res => {
        console.log('分享成功', res);
      },
    };
  },
  getLoginInfo() {
    return new Promise(resolve => {
      getlogininfo.getLoginInfo({
        type: 'live_room',
        success: (ret) => {
          this.setData({
            isGetLoginInfo: true,
          });
          resolve(true);
        },
        fail: (ret) => {
          this.setData({
            isGetLoginInfo: false,
          });
          resolve(false);
          wx.showModal({
            title: '提示',
            content: ret.errMsg,
            showCancel: false,
          });
        },
      });
    });
  },
});
